package frobagroup.services.frontEnd.impl;

import frobagroup.entities.backstage.CarouselFigure;
import frobagroup.entities.backstage.Comment;
import frobagroup.entities.backstage.ImageText;
import frobagroup.entities.backstage.Product;
import frobagroup.entities.frontEnd.UserProfile;
import frobagroup.pagination.PageableImpl;
import frobagroup.pagination.Pagination;
import frobagroup.repositories.backstage.CarouselFigureRepository;
import frobagroup.repositories.backstage.CommentRepository;
import frobagroup.repositories.backstage.ImageTextRepository;
import frobagroup.repositories.backstage.ProductRepository;
import frobagroup.repositories.frontEnd.UserProfileRepository;
import frobagroup.services.frontEnd.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Tinsley on 2018/5/15.
 */
@Service
public class HomeServiceImpl implements HomeService {


    @Autowired
    private CarouselFigureRepository carouselFigureRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ImageTextRepository imageTextRepository;
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private UserProfileRepository userProfileRepository;

    @Override
    public Map<Boolean,List<CarouselFigure>> findCarousels() {
        return carouselFigureRepository.findByStatus("active").stream().
                collect(Collectors.groupingBy(e -> e.isWhichType(),Collectors.toList()));
    }

    @Override
    public Map<String, Object> findProductDetial(String id, HttpServletRequest request) {
        Map params = new HashMap();
        String uId = (String)request.getAttribute("id");
        UserProfile userProfile = userProfileRepository.findByUId(uId);
        Product product = productRepository.findOne(id);
        if (product.getImgIds().size()>=1){
            List<ImageText> imageTextList = (List<ImageText>)imageTextRepository.findAll(product.getImgIds());
            params.put("imageTextList",imageTextList.stream().sorted(Comparator.comparing(ImageText::getOrder))
                    .collect(Collectors.toList()));
        }
        if (!StringUtils.isEmpty(product.getRelatedProductsIds()))
            params.put("relatedProducts",productRepository.findByStatusAndIdIn("active",product.getRelatedProductsIds()));


        List<Comment> comments;
        if (!StringUtils.isEmpty(uId)){

            if (userProfile.getFollowProductIds().contains(id))
                params.put("weatherFollow",Boolean.TRUE);
            else
                params.put("weatherFollow",Boolean.FALSE);

            comments = commentRepository.findByPIdAndStatus(id,"active");
            if (comments.size()>0) {
                comments.stream().map(e -> {
                    if (e.getCommentThumbsUpIds().contains(uId))
                        e.setWhetherCommentThumbsUp(Boolean.TRUE);
                    return e;
                }).collect(Collectors.toList());
            }

        }else
            comments = commentRepository.findByPId(id);
        if(comments.size()>0)
            comments = comments.stream().sorted(Comparator.comparing(Comment::getCommentDate).reversed()).collect(Collectors.toList());

        params.put("comments",comments);
        params.put("product",product);
        return params;
    }

    @Override
    public Pagination findExtensionProducts(Pagination pagination) {
        String sort = Objects.isNull(pagination.getSort()) ? "commitTime" : pagination.getSort();
        PageableImpl pageable = new PageableImpl(pagination.getPageNumber(),pagination.getPageSize(),
                new Sort(Objects.equals(Sort.Direction.DESC.name(),pagination.getDir()) ? Sort.Direction.DESC:Sort.Direction.ASC,sort));
        Page<Product> pages ;
        if (!StringUtils.isEmpty(pagination.getConditions().get("setTopType")))
            pages = productRepository.findBySetTopTypeAndStatus((String)pagination.getConditions().get("setTopType"),
                    (String)pagination.getConditions().get("status"), pageable);
        else
            pages = productRepository.findByMustCheckOutAndStatus(Boolean.parseBoolean((String)pagination.getConditions().get("mustCheckOut")),
                    (String)pagination.getConditions().get("status"), pageable);
        pagination.setContent(pages.getContent());
        pagination.setTotal(pages.getTotalElements());
        return pagination;
    }

    @Override
    public Pagination findProductsByConditions(Pagination pagination) {

        String sort = Objects.isNull(pagination.getSort()) ? "commitTime" : pagination.getSort();
        PageableImpl pageable = new PageableImpl(pagination.getPageNumber(),pagination.getPageSize(),
                new Sort(Objects.equals(Sort.Direction.DESC.name(),pagination.getDir()) ? Sort.Direction.DESC:Sort.Direction.ASC,sort));
        Page<Product> pages = null;
        if(!StringUtils.isEmpty(pagination.getConditions().get("type"))&&
                !StringUtils.isEmpty(pagination.getConditions().get("productName")))
            pages = productRepository.findByTypeAndStatusAndProductNameLike((String)pagination.getConditions().get("type"),
                    "active",(String)pagination.getConditions().get("productName"), pageable);
        if (StringUtils.isEmpty(pagination.getConditions().get("type"))&&
                !StringUtils.isEmpty(pagination.getConditions().get("productName")))
            pages = productRepository.findByStatusAndProductNameLike("active",
                    (String)pagination.getConditions().get("productName"), pageable);
        if (!StringUtils.isEmpty(pagination.getConditions().get("type"))&&
                StringUtils.isEmpty(pagination.getConditions().get("productName")))
            pages = productRepository.findByStatusAndType("active",
                    (String)pagination.getConditions().get("type"), pageable);

        if (StringUtils.isEmpty(pagination.getConditions().get("type"))&&
                StringUtils.isEmpty(pagination.getConditions().get("productName")))
            pages = productRepository.findAll(pageable);
        pagination.setContent(pages.getContent());
        pagination.setTotal(pages.getTotalElements());
        return pagination;

    }
}
